package com.waterworld.watch.home.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.waterworld.watch.R;
import com.waterworld.watch.common.activity.BaseActivity;
import com.waterworld.watch.common.bean.CourseBean;
import com.waterworld.watch.common.bean.UserInfoBean;
import com.waterworld.watch.common.customview.CommonPopupWindow;
import com.waterworld.watch.common.net.BaseObserverListener;
import com.waterworld.watch.common.net.BaseResultBean;
import com.waterworld.watch.common.util.ScreenAdapterUtil;
import com.waterworld.watch.common.util.TimeUtils;
import com.waterworld.watch.common.util.ToastUtils;
import com.waterworld.watch.home.adapter.ClassTimeAdapter;
import com.waterworld.watch.home.adapter.CourseAdapter;
import com.waterworld.watch.home.interfaces.IHomeManager;
import com.waterworld.watch.home.manager.HomeManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.carbswang.android.numberpickerview.library.NumberPickerView;

public class SkillCurriculumActivity extends BaseActivity {

    @BindView(R.id.parentView)
    LinearLayout parentView;

    @BindView(R.id.header_parent)
    LinearLayout header_parent;

    @BindView(R.id.header_back)
    ImageView header_back;

    @BindView(R.id.header_title)
    TextView header_title;

    @BindView(R.id.rl_close_watch)
    RelativeLayout rl_close_watch;

    @BindView(R.id.cb_is_close_in_class)
    CheckBox cb_is_close_in_class;

    @BindView(R.id.rv_class_time)
    RecyclerView rv_class_time;

    @BindView(R.id.btn_submit)
    Button btn_submit;

    @BindView(R.id.rv_week)
    RecyclerView rv_week;

    private IHomeManager iHomeManager = HomeManager.getInstance();

    private ClassTimeAdapter classTimeAdapter;
    private CourseAdapter adapter;

    private NumberPickerView course;
    private Button course_finish;

    private EditText et_custom_class;
    private Button btn_cancel;
    private Button btn_confirm;


    private NumberPickerView start_hour;
    private NumberPickerView start_minute;
    private NumberPickerView end_hour;
    private NumberPickerView end_minute;
    private Button btn_time_cancel;
    private Button btn_time_confirm;

    private CommonPopupWindow.LayoutGravity layoutGravity;
    private CommonPopupWindow coursePopupWindow;
    private CommonPopupWindow customClassWindow;

    private CommonPopupWindow courseTimePopupWindow;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_skill_curriculum);
        ButterKnife.bind(this);
        initView();
    }

    private void initView(){
        setViewSize(header_parent, ViewGroup.LayoutParams.MATCH_PARENT, ScreenAdapterUtil.getHeightPx(this)/10);
        header_back.setVisibility(View.VISIBLE);
        header_title.setVisibility(View.VISIBLE);
        header_title.setText(R.string.curriculum);
        if (UserInfoBean.getInstance().getWatchUser().getUserRole() == 0) {
            rl_close_watch.setVisibility(View.VISIBLE);
            btn_submit.setVisibility(View.VISIBLE);
        }
        if (iHomeManager != null) {
            iHomeManager.getCourse(new BaseObserverListener<BaseResultBean<CourseBean>>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtils.showShort(SkillCurriculumActivity.this, getString(R.string.data_error));
                    Log.e("nh",e.toString());
                }

                @Override
                public void onNext(BaseResultBean<CourseBean> baseResultBean) {
                    if (baseResultBean.getData() == null) {
                        CourseBean.getInstance().setCloseInClass(0);
                        CourseBean.getInstance().setCourse(new String[]{",,,,,,,",",,,,,,,",",,,,,,,",",,,,,,,",",,,,,,,"});
                        List<CourseBean.Time> list = new ArrayList<>();
                        list.add(new CourseBean.Time("08:00","08:45"));
                        list.add(new CourseBean.Time("08:55","09:40"));
                        list.add(new CourseBean.Time("10:00","10:45"));
                        list.add(new CourseBean.Time("10:55","11:40"));
                        list.add(new CourseBean.Time("13:30","14:15"));
                        list.add(new CourseBean.Time("14:25","15:10"));
                        list.add(new CourseBean.Time("15:20","16:05"));
                        list.add(new CourseBean.Time("16:15","17:00"));
                        CourseBean.getInstance().setTime(list);
                    }else {
                        CourseBean.getInstance().setCloseInClass(baseResultBean.getData().getCloseInClass());
                        CourseBean.getInstance().setCourse(baseResultBean.getData().getCourse());
                        CourseBean.getInstance().setTime(baseResultBean.getData().getTime());
                    }

                    //初始化上课禁用
                    cb_is_close_in_class.setChecked(CourseBean.getInstance().getCloseInClass() != 0);

                    //初始化时间
                    List<CourseBean.Time> list =  CourseBean.getInstance().getTime();
                    classTimeAdapter = new ClassTimeAdapter(SkillCurriculumActivity.this,list);
                    LinearLayoutManager linearLayoutManager_classTime = new LinearLayoutManager(SkillCurriculumActivity.this);
                    linearLayoutManager_classTime.setOrientation(LinearLayoutManager.VERTICAL);
                    rv_class_time.setLayoutManager(linearLayoutManager_classTime);
                    rv_class_time.setAdapter(classTimeAdapter);


                    //初始化课程
                    List<String> courseList = new ArrayList<>();
                    for (int i=0;i<CourseBean.getInstance().getCourse().length;i++) {
                        String[] courses = CourseBean.getInstance().getCourse()[i].split(",",-1);
                        courseList.addAll(Arrays.asList(courses));
                    }

                    adapter = new CourseAdapter(SkillCurriculumActivity.this,courseList);
                    GridLayoutManager gridLayoutManager = new GridLayoutManager(SkillCurriculumActivity.this,8);
                    gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    rv_week.setLayoutManager(gridLayoutManager);
                    rv_week.setAdapter(adapter);

                    if (UserInfoBean.getInstance().getWatchUser().getUserRole() == 0) {
                        classTimeAdapter.setOnItemClick(new ClassTimeAdapter.SetonClickListener() {
                            @Override
                            public void onClick(View view, int position) {
                                backgroundAlpha(0.5f);
                                courseTimePopupWindow = new CommonPopupWindow(SkillCurriculumActivity.this,R.layout.popup_course_time,(int)(ScreenAdapterUtil.getWidthPx(SkillCurriculumActivity.this)*0.9),(int)(ScreenAdapterUtil.getHeightPx(SkillCurriculumActivity.this)*0.9)){
                                    @Override
                                    protected void initView() {
                                        View view2 = getContentView();
                                        start_hour = view2.findViewById(R.id.start_hour);
                                        start_minute = view2.findViewById(R.id.start_minute);
                                        end_hour = view2.findViewById(R.id.end_hour);
                                        end_minute = view2.findViewById(R.id.end_minute);
                                        btn_time_cancel = view2.findViewById(R.id.btn_time_cancel);
                                        btn_time_confirm = view2.findViewById(R.id.btn_time_confirm);

                                        final String[] hourArray = TimeUtils.returnStringArray(0,23);
                                        final String[] minuteArray = TimeUtils.returnStringArray(0,59);

                                        start_hour.setDisplayedValues(hourArray);
                                        start_hour.setMinValue(0);
                                        start_hour.setMaxValue(hourArray.length-1);
                                        start_hour.setValue(Integer.parseInt(list.get(position).getStartTime().split(":")[0]));

                                        start_minute.setDisplayedValues(minuteArray);
                                        start_minute.setMinValue(0);
                                        start_minute.setMaxValue(minuteArray.length-1);
                                        start_minute.setValue(Integer.parseInt(list.get(position).getStartTime().split(":")[1]));

                                        end_hour.setDisplayedValues(hourArray);
                                        end_hour.setMinValue(0);
                                        end_hour.setMaxValue(hourArray.length-1);
                                        end_hour.setValue(Integer.parseInt(list.get(position).getEndTime().split(":")[0]));

                                        end_minute.setDisplayedValues(minuteArray);
                                        end_minute.setMinValue(0);
                                        end_minute.setMaxValue(minuteArray.length-1);
                                        end_minute.setValue(Integer.parseInt(list.get(position).getEndTime().split(":")[1]));
                                    }

                                    @Override
                                    protected void initEvent() {
                                        btn_time_cancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                courseTimePopupWindow.getPopupWindow().dismiss();
                                            }
                                        });
                                        btn_time_confirm.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (Integer.parseInt(start_hour.getContentByCurrValue()) < Integer.parseInt(end_hour.getContentByCurrValue()) ||
                                                        (Integer.parseInt(start_hour.getContentByCurrValue()) == Integer.parseInt(end_hour.getContentByCurrValue())
                                                                && Integer.parseInt(start_minute.getContentByCurrValue()) < Integer.parseInt(end_minute.getContentByCurrValue()))) {
                                                    list.get(position).setStartTime(start_hour.getContentByCurrValue() + ":" + start_minute.getContentByCurrValue());
                                                    list.get(position).setEndTime(end_hour.getContentByCurrValue() + ":" + end_minute.getContentByCurrValue());
                                                    courseTimePopupWindow.getPopupWindow().dismiss();
                                                    classTimeAdapter.notifyItemChanged(position);
                                                } else {
                                                    ToastUtils.showShort(SkillCurriculumActivity.this,"开始时间必须晚于结束时间");
                                                }
                                            }
                                        });
                                    }
                                };
                                courseTimePopupWindow.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                                    @Override
                                    public void onDismiss() {
                                        backgroundAlpha(1.0f);
                                    }
                                });
                                layoutGravity = new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.CENTER_HORIZONTAL | CommonPopupWindow.LayoutGravity.CENTER_VERTICAL);
                                courseTimePopupWindow.showBashOfAnchor(parentView, layoutGravity, 0, 0);
                            }
                        });
                        adapter.setOnItemClick(new CourseAdapter.SetonClickListener() {
                            @Override
                            public void onClick(View view, int position) {
                                backgroundAlpha(0.5f);
                                final String[] genderArray = {"语文", "数学","英语","体育","自定义"};
                                coursePopupWindow = new CommonPopupWindow(SkillCurriculumActivity.this, R.layout.popup_course_picker,
                                        ScreenAdapterUtil.getWidthPx(SkillCurriculumActivity.this),
                                        (int) (ScreenAdapterUtil.getHeightPx(SkillCurriculumActivity.this) * 0.3)) {
                                    @Override
                                    protected void initView() {
                                        View view = getContentView();
                                        course_finish = view.findViewById(R.id.btn_course_finish);
                                        course = view.findViewById(R.id.gender);
                                        course.setDisplayedValues(genderArray);
                                        course.setMinValue(0);
                                        course.setMaxValue(genderArray.length - 1);
                                        course.setValue(0);
                                    }

                                    @Override
                                    protected void initEvent() {
                                        course_finish.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                if ("自定义".equals(course.getContentByCurrValue())) {
                                                    customClassWindow = new CommonPopupWindow(SkillCurriculumActivity.this, R.layout.popup_custom_class,
                                                            (int)(ScreenAdapterUtil.getWidthPx(SkillCurriculumActivity.this) * 0.8),
                                                            (int) (ScreenAdapterUtil.getHeightPx(SkillCurriculumActivity.this) * 0.2)) {
                                                        @Override
                                                        protected void initView() {
                                                            View view1 = getContentView();
                                                            et_custom_class = view1.findViewById(R.id.et_custom_class);
                                                            btn_cancel = view1.findViewById(R.id.btn_cancel);
                                                            btn_confirm = view1.findViewById(R.id.btn_confirm);
                                                        }

                                                        @Override
                                                        protected void initEvent() {
                                                            btn_cancel.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    customClassWindow.getPopupWindow().dismiss();
                                                                }
                                                            });
                                                            btn_confirm.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    courseList.set(position,et_custom_class.getText().toString());
                                                                    customClassWindow.getPopupWindow().dismiss();
                                                                    adapter.notifyItemChanged(position);
                                                                    coursePopupWindow.getPopupWindow().dismiss();
                                                                }
                                                            });
                                                        }
                                                    };
                                                    layoutGravity = new CommonPopupWindow.LayoutGravity(LayoutGravity.CENTER_HORIZONTAL | LayoutGravity.CENTER_VERTICAL);
                                                    customClassWindow.showBashOfAnchor(parentView,layoutGravity,0,0);
                                                } else {
                                                    courseList.set(position, course.getContentByCurrValue());
                                                    adapter.notifyItemChanged(position);
                                                    coursePopupWindow.getPopupWindow().dismiss();
                                                }

                                            }
                                        });
                                    }
                                };

                                coursePopupWindow.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                                    @Override
                                    public void onDismiss() {
                                        backgroundAlpha(1.0f);
                                    }
                                });
                                layoutGravity = new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.CENTER_HORIZONTAL | CommonPopupWindow.LayoutGravity.ALIGN_BOTTOM);
                                coursePopupWindow.showBashOfAnchor(parentView, layoutGravity, 0, 0);
                            }
                        });
                    }
                }
            });

        }
    }

    @OnClick(R.id.header_back)
    void onBack() {
        finish();
    }

    @OnClick(R.id.btn_submit)
    void onSubmit() {
        if (iHomeManager != null) {
            Map<String,Object> map = new HashMap<>();
            map.put("isCloseInClass",cb_is_close_in_class.isChecked() ? 1 : 0);
            int week_day = adapter.getData().size()/classTimeAdapter.getData().size();
            int course_count = classTimeAdapter.getData().size();
            String[][] temp1 = new String[week_day][course_count];
            String[] course = new String[week_day];
            for (int i=0;i<week_day;i++) {
                for (int j=0;j<course_count;j++) {
                    temp1[i][j] = adapter.getData().get(i * course_count + j);
                }
                course[i] = arrayToString(temp1[i]);
            }
            map.put("course",course);

            List<Map<String,String>> time = new ArrayList<Map<String,String>>();
            for (int i=0;i<classTimeAdapter.getData().size();i++) {
                CourseBean.Time temp2 = classTimeAdapter.getData().get(i);
                Map<String,String> map_time = new HashMap<>();
                map_time.put("startTime",temp2.getStartTime());
                map_time.put("endTime",temp2.getEndTime());
                time.add(map_time);
            }

            map.put("time",time);

            String json = JSONObject.toJSONString(map);
            iHomeManager.uploadCourse(json, new BaseObserverListener<BaseResultBean>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(BaseResultBean baseResultBean) {
                    if (baseResultBean.getCode() == 0) {
                        ToastUtils.showShort(SkillCurriculumActivity.this,getString(R.string.upload_success));
                    }
                }
            });
        }
    }


    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        this.getWindow().setAttributes(lp);
    }

    private String arrayToString(String[] array) {
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<array.length;i++) {
            if(i<array.length-1){
                sb.append(array[i]+",");
            }else {
                sb.append(array[i]);
            }
        }
        return sb.toString();
    }
}
